var passwords = {};
passwords.Application = function(){};
core.extendClass('passwords.Application', 'core.JSApplication');

passwords.Grid = function(){};
core.extendClass('passwords.Grid', 'core.JSFrame');

passwords.Grid.prototype.loadContents = function(aData){
    var instance = this;
    this.newButton = new core.form.Button({
        text: 'New',
        handler: function(){
            instance.send({
                method: 'newPassword',
                disable: instance.newButton
            });
        }
    });
    this.lockButton = new core.form.Button({
        text: 'Lock',
        handler: function(){
            var row = instance.grid.selectedRow;
            if(row){
                $(row[1]).val('');
                $(row[2]).val('');
            }
            instance.send({
                method: 'lockPassword',
                disable: instance.lockButton
            });
        }
    });
    this.settingsButton = new core.form.Button({
        text: 'Options',
        handler: function(){
            instance.send({
                method: 'showSettings',
                disable: instance.lockButton
            });
        }
    });
//#ifdef DESKTOP
    this.grid = new core.grid.GridPanel({
        allowRowSelect: true,
        frame: this,
        headerCaptions: ['Name:', 'Login:', 'Password:', 'Show:'],
        columns: '0.5, 0.25, 0.25, 90',
        idIndex: 4
    });
    this.grid.minWidth = 450;
//#endif
//#ifdef MOBILE
    this.grid = new core.grid.GridPanel({
        allowRowSelect: true,
        frame: this,
        headerCaptions: ['Name:', 'Show:'],
        columns: '1, 90',
        idIndex: 2
    });
//#endif
    this.grid.on('add_item', function(grid, aData){
//        core.log('Item added', aData.name, aData.id);
        var name = new core.newDiv(null, 'passwords_name');

        $(name).html(grid.imagesToHTMLSprite('passwords_icns passwords_icn_password')+'&nbsp;'+aData.name);
//#ifdef DESKTOP

        var login = new core.newElement(null, 'input', 'passwords_field');
        var pass = new core.newElement(null, 'input', 'passwords_field');
        $(login).attr('readonly', 'true').focus(function(){
            $(this).select();
        });
        $(pass).attr('readonly', 'true').focus(function(){
            $(this).select();
        });
//#endif
        var btn = new core.form.Button({
            text: 'Show',
            align: 'center',
            handler: function(button){
                //#ifdef DESKTOP
                instance.send({
                    method: 'showPassword',
                    message: {
                        id: button.rowid
                    },
                    ok: function(aData){
                        instance.grid.selectRow(button.rowid);
                        var row = instance.grid.getRow(button.rowid);
                        if(row){
                            $(row[1]).val(aData.login);
                            $(row[2]).val(aData.password).focus();
                        }
                    },
                    disable: button
                });
                //#endif

                //#ifdef MOBILE
                instance.send({
                    method: 'showPasswordMobile',
                    message: {
                        id: button.rowid
                    },
                    disable: button
                });
                //#endif

            }
        });
        btn.enableDD({
            area: core.desktop.items[0],
            detectBy: name,
            clone: name,
            leftAligned: true
        });
        btn.rowid = aData.id;
//#ifdef DESKTOP
        return [name, login, pass, btn, aData.id];
//#endif
//#ifdef MOBILE
        return [name, btn, aData.id];
//#endif
    }).on('dblclick', function(el, event, id, row){
        if(id && row){
            instance.send({
                method: 'editPassword',
                message:{
                    id: id
                },
                disable: instance.grid
            });
        }
    }).on('unselect', function(el, event, id, row){
        //#ifdef DESKTOP
        $(row[1]).val('');
        $(row[2]).val('');
        //#endif
    });
    this.frame.addToolbar(new core.Tabs({
        toolbar: true,
        elements: [this.newButton, this.lockButton, this.settingsButton]
    }));
    this.setContent([this.grid], '1', '1');
    this.send({
        method: 'loadGrid',
        disable: this.grid,
        ok: function(aData){
            instance.grid.loadGrid(aData);
        }
    });
};

passwords.Categories = function(){};
core.extendClass('passwords.Categories', 'core.JSFrame');

passwords.Categories.prototype.loadContents = function(aData){
//    core.log('load categories');
    var instance = this;
    this.newFolder = new core.form.Button({
        text: 'New',
        handler: function(){
            instance.send({
                method: 'newFolder',
                disable: instance.tree
            });
        }
    });
    this.editFolder = new core.form.Button({
        text: 'Edit',
        disabled: true,
        handler: function(){
            instance.send({
                method: 'editFolder',
                disable: instance.tree
            });
        }
    });
    this.removeFolder = new core.form.Button({
        text: 'Remove',
        disabled: true,
        handler: function(){
            instance.send({
                method: 'removeFolder',
                disable: instance.tree
            });
        }
    });
    this.frame.addToolbar(new core.Tabs({
        toolbar: true,
        elements: [this.newFolder, this.editFolder, this.removeFolder]
    }));
    this.tree = new core.tree.TreePanel({
        frame: this
    });
    this.tree.on('select', function(tree, event, item){
        var table = instance.application.getFrame('table');
        instance.send({
            method: 'selectionChanged',
            message: {
                id: item?item.id: null
            },
            disable: table?table.grid: null
        });
        instance.editFolder.setDisabled(item?false:true);
        instance.removeFolder.setDisabled(item?false:true);
        return false;
    }).on('accept_target', function(tree, e, item, target){
        if(item.rowid)
            return true;
        return false;
    }).on('dd_end', function(tree, e, item, target){
        var table = instance.application.getFrame('table');
        instance.send({
            method: 'movePassword',
            message: {
                password: item.rowid,
                folder: target.id
            },
            disable: table? table.grid: null
        });
    });
    this.setContent([this.tree], '1', '1');
    this.tree.reloadTree();
};

passwords.CategorieEditor = function(){};
core.extendClass('passwords.CategorieEditor', 'core.JSDialog');

passwords.CategorieEditor.prototype.createDialog = function(aData){
    var instance = this;
    var editor = new core.form.TextField({
        id: 'name'
    });
    var dlg = new core.Dialog({
        title: aData.new_cat?'Create new folder:':'Edit folder:',
        maxWidth: 300,
        data: aData,
        items:[
            core.createLabel('Name:'),
            editor, core.ui.createRightButtons({
                colspan: 2,
                ok: function(){
                    instance.send({
                        method: 'okClick',
                        message: dlg.body.getValue(),
                        disable: dlg
                    });
                },
                cancel: function(){
                    instance.send({
                        method: 'closeDialog',
                        disable: dlg
                    });
                }
            })
        ],
        rows: 'd, d',
        columns: '0.2, 0.8',
        defaultItem: editor
    });
    return dlg;
};

passwords.EntryEditor = function(){};
core.extendClass('passwords.EntryEditor', 'core.JSDialog');

passwords.EntryEditor.hiddenText = "*** Hidden ***";

passwords.EntryEditor.prototype.createDialog = function(aData){
    var instance = this;
//    core.log('Creating dialog EntryEditor...');
    this.name = new core.form.TextField({
        id: 'name',
        colspan: 2
    });
    this.login = new core.form.TextField({
        id: 'login'
    });
    this.password1 = new core.form.TextField({
        id: 'password1'
    });
    this.password2 = new core.form.TextField({
        id: 'password2'
    });
    this.showButton = new core.form.Button({
        text: 'Show',
        handler: function(){
            instance.send({
                method: 'showPassword',
                message: dlg.body.getValue(),
                disableItem: dlg,
                ok: function(aData){
                    instance.changePasswordStyle(aData.pass_hidden, aData);
                }
            });
        }
    });
    this.generateButton = new core.form.Button({
        text: 'Generate password',
        minWidth: 150,
        align: 'right',
        colspan: 2,
        handler: function(){
            instance.send({
                method: 'generatePassword',
                message: dlg.body.getValue(),
                disableItem: dlg,
                ok: function(aData){
                    instance.password1.setValue(aData.password);
                    instance.password2.setValue(aData.password);
                }
            });
        }
    });
//    core.log('Creating dialog before constructor EntryEditor...');
    var dlg = new core.Dialog({
        title: 'Password editor:',
        maxWidth: 400,
        data: aData,
        items:[
            core.createLabel('Name:'),
            this.name,
            core.createLabel("URL:"),
            new core.form.TextField({
                id: 'url',
                colspan: 2
            }),
            core.createLabel('Login name:'),
            this.login,
            this.showButton,
            core.createLabel('Password:'),
            this.password1,
            core.createLabel(''),
            core.createLabel('Repeat password:'),
            this.password2,
            core.createLabel(''),
            new core.Box({
                colspan: 3,
                items:[
                    new core.form.CheckBox({
                        id: 'use_letters',
                        colspan: 2,
                        text: 'Use letters: A-Z, a-z'
                    }),
                    new core.form.CheckBox({
                        id: 'use_numbers',
                        colspan: 2,
                        text: 'Use numbers: 0-9'
                    }),
                    new core.form.CheckBox({
                        id: 'use_symbols',
                        colspan: 2,
                        text: 'Use symbols: ~!?,.@#$%^&*(){}[]-+=_/\\'
                    }),
                    new core.form.TextField({
                        minWidth: 20,
                        id: 'pass_length'
                    }),
                    new core.Label({
                        align: 'left',
                        text: 'characters long'
                    }),
                ],
                rows: 'd, d, d, d',
                columns: 'd, 1'
            }),
            new core.Label({
                align: 'left',
                text: 'Notes:'
            }),
            this.generateButton,
            new core.form.TextArea({
               colspan: 3,
               id: 'notes',
               minHeight: 35
            }),
            core.ui.createButtons({
                colspan: 3,
                buttons: aData.edit?['Ok', 'Cancel', 'Remove']:['Ok', 'Cancel'],
                align: 'right',
                handler: function(index){
                    switch(index){
                        case 0:
                            instance.send({
                                method: 'okClick',
                                message: dlg.body.getValue(),
                                disable: dlg
                            });
                            break;
                        case 1:
                            instance.send({
                                method: 'closeDialog',
                                disable: dlg
                            });
                            break;
                        case 2:
                            instance.send({
                                method: 'removeClick',
                                message: dlg.body.getValue(),
                                disable: dlg
                            });
                            break;
                    }
                }
            })
        ],
        rows: 'd, d, d, d, d, d, d, d, d',
        columns: '0.2, 0.8, d',
        defaultItem: this.name
    });
    this.changePasswordStyle(aData.pass_hidden, aData);
//    core.log('Starting dialog...');
    return dlg;
};

passwords.EntryEditor.prototype.changePasswordStyle = function(aHidden, aData){
    this.showButton.setText(aHidden?'Show':'Hide');
    this.generateButton.setDisabled(aHidden);
    $(this.login.control).attr('readonly', aHidden);
    $(this.password1.control).attr('readonly', aHidden);
    $(this.password2.control).attr('readonly', aHidden);
    this.login.setValue(aHidden?passwords.EntryEditor.hiddenText:aData.login);
    this.password1.setValue(aHidden?passwords.EntryEditor.hiddenText:aData.password1);
    this.password2.setValue(aHidden?passwords.EntryEditor.hiddenText:aData.password2);
}

passwords.MasterPassword = function(){};
core.extendClass('passwords.MasterPassword', 'core.JSDialog');

passwords.MasterPassword.prototype.createDialog = function(aData){
    var instance = this;
    var dlg = null;
    var pass1 = new core.form.TextField({
        id: 'pass1',
        password: true
    });
    if(aData.new_pass){
        dlg = new core.Dialog({
            title: 'Create master password:',
            maxWidth: 350,
            items:[
                core.createLabel('New password:'),
                pass1,
                core.createLabel('Confirm password:'),
                new core.form.TextField({
                    id: 'pass2',
                    password: true
                }),
                core.ui.createRightButtons({
                    colspan: 2,
                    okCaption: 'Ok',
                    ok: function(){
                        instance.send({
                            method: 'okClick',
                            message: dlg.body.getValue(),
                            disable: dlg
                        });
                    },
                    cancel: function(){
                        instance.send({
                            method: 'closeDialog',
                            disable: dlg
                        });
                    }
                })
            ],
            rows: 'd, d, d',
            columns: '0.2, 0.8',
            defaultItem: pass1
        });
    }else{
        dlg = new core.Dialog({
            title: 'Enter master password:',
            maxWidth: 350,
            items:[
                core.createLabel('Password:'),
                pass1,
                core.ui.createRightButtons({
                    colspan: 2,
                    okCaption: 'Ok',
                    ok: function(){
                        instance.send({
                            method: 'okClick',
                            message: dlg.body.getValue(),
                            disable: dlg
                        });
                    },
                    cancel: function(){
                        instance.send({
                            method: 'closeDialog',
                            disable: dlg
                        });
                    }
                })
            ],
            rows: 'd, d',
            columns: '0.2, 0.8',
            defaultItem: pass1
        });
    }
    return dlg;
};

passwords.MobileView = function(){};
core.extendClass('passwords.MobileView', 'core.JSDialog');

passwords.MobileView.prototype.createDialog = function(aData){
    var instance = this;
    var dlg = new core.Dialog({
        title: 'Password:',
        maxWidth: 350,
        items:[
            new core.Label({
                text: 'Name:',
                align: 'left'
            }),
            new core.Label({
                text: aData.name,
                align: 'left'
            }),
            new core.Label({
                text: 'Login:',
                align: 'left'
            }),
            new core.Label({
                text: aData.login,
                align: 'left'
            }),
            new core.Label({
                text: 'Password:',
                align: 'left'
            }),
            new core.Label({
                text: aData.password,
                align: 'left'
            }), core.ui.createButtons({
                buttons: ['Ok', 'Edit'],
                align: 'center',
                handler: function(index){
                    instance.send({
                        method: index==0?'closeDialog':'editEntry',
                        disable: dlg
                    });
                }
            })
        ], rows: 'd, d, d, d, d, d, d',
        columns: '1'
    });
    return dlg;
};

passwords.Settings = function(){};
core.extendClass('passwords.Settings', 'core.JSDialog');

passwords.Settings.prototype.createDialog = function(aData){
    var instance = this;
    var dlg = new core.Dialog({
        title: 'Password manager settings:',
        maxWidth: 300,
        items:[
            new core.Label({
                text: 'Change master password:',
                colspan: 2,
                align: 'left'
            }),
            core.createLabel('Old password:'),
            new core.form.TextField({
                id: 'old_pass',
                password: true
            }),
            core.createLabel('New password:'),
            new core.form.TextField({
                id: 'new_pass',
                password: true
            }),
            core.createLabel('Retype password:'),
            new core.form.TextField({
                id: 'new_pass2',
                password: true
            }),
            core.ui.createButtons({
                colspan: 2,
                align: 'right',
                buttons: ['Ok', 'Cancel'],
                handler: function(index){
                    instance.send({
                        method: index==0?'okClick':'closeDialog',
                        message: dlg.body.getValue(),
                        disable: dlg
                    });
                }
            })
        ],
        columns: '0.3, 0.7',
        rows: 'd, d, d, d, d'
    });
    return dlg;
};
